package com.atguigu.datastream.day06;


import com.atguigu.datastream.bean.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * ClassName: Flink08_Flink_ForMonotonous_WaterMark
 * Package: com.atguigu.day05
 * Description:
 *           基于处理事时间的定时器
 * @Author ChenJun
 * @Create 2023/4/11 18:31
 * @Version 1.0
 */
public class Flink05_Flink_Timer_ProcessTime {

    public static void main(String[] args) throws Exception {

        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        //2.从端口读取数据
        DataStreamSource<String> streamSource = env.socketTextStream("localhost", 9999);

        //3.将数据转为JavaBean，为了方便提取数据
        SingleOutputStreamOperator<WaterSensor> waterSensorDStream = streamSource.map(new MapFunction<String, WaterSensor>() {
            @Override
            public WaterSensor map(String value) throws Exception {
                String[] split = value.split(",");
                return new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2]));
            }
        });

        //4.将相同id的数据聚合到一块
        KeyedStream<WaterSensor, Tuple> keyedStream = waterSensorDStream.keyBy("id");

        //TODO 5.使用基于处理时间的定时器
        SingleOutputStreamOperator<String> result = keyedStream.process(new KeyedProcessFunction<Tuple, WaterSensor, String>() {
            @Override
            public void processElement(WaterSensor value, KeyedProcessFunction<Tuple, WaterSensor, String>.Context ctx, Collector<String> out) throws Exception {
                // TODO 定时时间为5s 5s后定时器触发打印一句话
                System.out.println("当前时间：" + (System.currentTimeMillis() /1000));
                long curTime = ctx.timerService().currentProcessingTime();
                long time = curTime + 5000;
                ctx.timerService().registerProcessingTimeTimer(time);
            }

            /**
             * 回调函数 在定时器触发后调用
             * @param timestamp 定时器触发的时间
             * @param ctx 上下文对象
             * @param out 采集器
             * @throws Exception
             */
            @Override
            public void onTimer(long timestamp, KeyedProcessFunction<Tuple, WaterSensor, String>.OnTimerContext ctx, Collector<String> out) throws Exception {
//                out.collect("报警了，当前时间：" + (System.currentTimeMillis() / 1000));
                out.collect("报警了，当前时间：" + timestamp/ 1000);
            }
        });

        result.print();

        env.execute();

    }


}
